package com.emperor.employee.app;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;

import com.emperor.cashier.app.CashierAppCtrl;
import com.emperor.core.app.App;
import com.emperor.core.app.AppBase;
import com.emperor.core.app.AppConstant;
import com.emperor.customer.app.CustomerAppCtrl;
import com.emperor.employee.logic.Employee;
import com.emperor.util.HibernateUtil;
import com.swtdesigner.SWTResourceManager;

public class EmployeeAppEnq extends AppBase implements App {

	protected Shell shell;
	public static Logger log = Logger.getLogger(EmployeeAppEnq.class);
	
	public EmployeeAppEnq() {
		super();
	}
	
	public EmployeeAppEnq(Map<String, Object> params) {
		super();
		this.params = params;
	}

	/**
	 * Launch the application
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			EmployeeAppEnq window = new EmployeeAppEnq();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window
	 */
	public void open() {
		final Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}

	/**
	 * Create contents of the window
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setBackgroundImage(SWTResourceManager.getImage(EmployeeAppEnq.class, "/img/main.jpg"));
		shell.setImage(SWTResourceManager.getImage(EmployeeAppEnq.class, "/img/iMac OSX.png"));
		shell.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
		shell.setSize(1280, 800);
		shell.setText("Search Employee");

		initScreen(shell, getParams());
		
		final Composite composite = new Composite(shell, SWT.NONE);
		composite.setBounds(0, 50, 892, 85);

		final Label employeeNameLabel = new Label(composite, SWT.NONE);
		employeeNameLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		employeeNameLabel.setText("Employee Name");
		employeeNameLabel.setBounds(10, 47, 120, 20);

		final Text text = new Text(composite, SWT.BORDER);
		text.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		text.setToolTipText("name");
		text.setBounds(134, 44, 282, 30);

		final Table table = new Table(shell, SWT.FULL_SELECTION | SWT.BORDER);
		table.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		table.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(final MouseEvent e) {
				TableItem[] items = table.getSelection();
				if (items != null && items.length > 0) {
					for (int i=0; i<items.length; i++) {
						TableItem item = items[i];
						if (item.getData() != null) {
							Employee employee = (Employee)item.getData();
							getParams().put(EmployeeAppCtrl.EMP_ID, employee.getId());
							
							getParams().put(AppConstant.APPCTRL, EmployeeAppCtrl.EMP_CTRL);
							getParams().put(AppConstant.ACTION, EmployeeAppCtrl.EMP_MGM);
							getShell().close();
						}
					}
				}
			}
		});
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		table.setBounds(10, 145, 1252, 438);
		
		final Label messageLabel = new Label(composite, SWT.NONE);
		messageLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		messageLabel.setText("Please key in the employee name to search.");
		messageLabel.setBounds(11, 10, 871, 20);
		
		final Button searchButton = new Button(composite, SWT.NONE);
		searchButton.setImage(SWTResourceManager.getImage(EmployeeAppEnq.class, "/img/Zoom-in.png"));
		searchButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		searchButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				populateTable(table, text, messageLabel);
			}
		});
		searchButton.setText("Search");
		searchButton.setBounds(422, 42, 90, 30);

		final TableColumn newColumnTableColumn = new TableColumn(table, SWT.NONE);
		newColumnTableColumn.setWidth(64);
		newColumnTableColumn.setText("No.");

		final TableColumn newColumnTableColumn_1 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_1.setWidth(397);
		newColumnTableColumn_1.setText("Name");

		final TableColumn newColumnTableColumn_2 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_2.setWidth(211);
		newColumnTableColumn_2.setText("Code");

		final TableColumn newColumnTableColumn_3 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_3.setWidth(261);
		newColumnTableColumn_3.setText("IC");

		final Button addNewEmployeButton = new Button(shell, SWT.NONE);
		addNewEmployeButton.setImage(SWTResourceManager.getImage(EmployeeAppEnq.class, "/img/Symbol-Add.png"));
		addNewEmployeButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		addNewEmployeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				getParams().put(AppConstant.APPCTRL, EmployeeAppCtrl.EMP_CTRL);
				getParams().put(AppConstant.ACTION, EmployeeAppCtrl.EMP_NEW);
				getShell().close();
			}
		});
		addNewEmployeButton.setText("Add");
		addNewEmployeButton.setBounds(10, 589, 65, 30);
		//
		buildStandardMenu(getShell(), getParams(), CashierAppCtrl.CASHIER_CTRL, CashierAppCtrl.CASHIER_FORM);
		populateTable(table, text, messageLabel);
		populateMsg(messageLabel);

		final Button updateEmployeeButton = new Button(shell, SWT.NONE);
		updateEmployeeButton.setImage(SWTResourceManager.getImage(EmployeeAppEnq.class, "/img/Edit.png"));
		updateEmployeeButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		updateEmployeeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				TableItem[] items = table.getSelection();
				if (items != null && items.length > 0) {
					for (int i=0; i<items.length; i++) {
						TableItem item = items[i];
						if (item.getData() != null) {
							Employee employee = (Employee)item.getData();
							getParams().put(EmployeeAppCtrl.EMP_ID, employee.getId());
							
							getParams().put(AppConstant.APPCTRL, EmployeeAppCtrl.EMP_CTRL);
							getParams().put(AppConstant.ACTION, EmployeeAppCtrl.EMP_MGM);
							getShell().close();
						}
					}
				}
			}
		});
		updateEmployeeButton.setText("Update");
		updateEmployeeButton.setBounds(81, 589, 90, 30);

		final Button deleteButton = new Button(shell, SWT.NONE);
		deleteButton.setVisible(false);
		deleteButton.setImage(SWTResourceManager.getImage(EmployeeAppEnq.class, "/img/Symbol-Delete.png"));
		deleteButton.setBounds(177, 687, 85, 30);
		deleteButton.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		deleteButton.setText("Delete");
	}

	public Shell getShell() {
		return shell;
	}

	public void setShell(Shell shell) {
		this.shell = shell;
	}

	public void populateTable(Table table, Text text, Label label) {
		StringBuffer sb = new StringBuffer();
		table.clearAll();
		table.removeAll();
		table.redraw();
		int count = 0;
		try {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			String name = text.getText();
			session.beginTransaction();
			// TODO Replace with StringUtills
			List<Employee> employees = new ArrayList<Employee>();
			Criteria cris = session.createCriteria(Employee.class);
			if (!"".equals(name.trim())) {
				cris.add(Expression.like(Employee.FLD_NAME, "%" + name + "%"));
			}
			employees = cris.list();
			
			for (Iterator<Employee> iter = employees.iterator(); iter.hasNext();) {
				Employee employee = iter.next();
				count++;
				TableItem item = new TableItem(table, SWT.BORDER);
				item.setText(new String[] {count + ".", employee.getName(), employee.getCode(), employee.getIc()});
				item.setData(employee);
			}
			sb.append(count).append(" employee(s) found.");
		} catch(Exception e) {
			sb.append("No result found. [").append(e.getMessage()).append("]");
			log.error(sb.toString(), e);
		}
		label.setText(sb.toString());
	}
	
	private void populateMsg(Label label) {
		try {
			if (getParams().get(EmployeeAppCtrl.EMP_MSG) != null) {
				String msg = (String)getParams().get(EmployeeAppCtrl.EMP_MSG);
				label.setText(msg);
			}
		} catch(Exception e) {
			log.error(e.getMessage(), e);
		}
	}
}
